var util = require('../../utils/util');
var wxApi = require('../../utils/wxApi');
var wxRequest = require('../../utils/wxRequest');
import config from '../../utils/config';
import { $wuxDialog } from '../../components/wux'

var wxCharts = require('../../utils/chart');

var WxParse = require('../../wxParse/wxParse.js');

var QQMapWX = require('../../utils/qqmap-wx-jssdk.min');
  var qqmapsdk;


var lineChart = null;

var app = getApp();
var that;


Page(
     
    {
  data: {
    user: {}
    ,isload:0
    ,sysset:{}
    ,istcVisible: false
    ,istcVisible2: false
      ,istcVisible3: false
       ,istcVisible4: false
      ,istcVisible5: false
      ,istcVisiblead:false
      ,adimg:""
      ,adw:0
      ,adh:0
      ,adurl:""
      ,zskb:0
     ,kbdays:0
    ,opop:0
    ,stop: 1000
    ,sleft: 1000
    ,userimg:"https://app.dkcake.com/images/touxiang.png"
    ,stepall:0
    ,step:0
    ,date:null
    ,isgetkb:false
    ,isgl:false
    ,isadmin:false
    ,isload:true
    ,kbobj:{kb:0,kbyd:0,kbxf:0}
    ,kblimit:0

    ,xh_cake:0
    ,xh_cal:0
    ,encryptedData:null
    ,windowWidth:300
    ,cls1:""
    ,cls2:""
    ,cls3:""
    ,cls4:""
    ,adinfos:[]
    ,isshowad:true
    ,getkb:0
      ,sheight:555
   ,sh:296
      ,swidth:375
      ,hidan:false
      ,tc:0
      ,addr:"--"
        ,pm:"--"
      , quality:"--"
      , measure:"--"
      , affect:"--"
      ,hidpm:true
     ,fxuid:0
      ,userinfotc:  true
	  
  },

  onShareAppMessage: function () {
      return app.getShare();
      //return {title:"D几名,邀请您",path:"pages/index/index",imageUrl:"https://app.dkcake.com/images/share.jpg"};
  },

  onPullDownRefresh:function(){
    that.loadData();
  },
  
  onReady:function(){
    that.data.isload=0;
  },
  onHide:function(){
      //that.data.tc=0;
      //clearTimeout(this.runcheck);
  },
  tc_back:function(){
      var animation = wx.createAnimation({
          timingFunction: "linear",
      })
      animation.scale(0.1, 0.1).step();

      this.setData({
          coverAlphaAnim: animation.export(),
          opop: 1,
          istcVisible5: true,
          zskb:that.data.zskb
      });

      animation.scale(1, 1).step({ duration: 250 });
      this.setData({
          coverAlphaAnim: animation.export()
      });
  }
  ,closeTc:function(){
    this.setData({
        istcVisible: false,
        canIUse:false
    });
  },
  closeTc2:function(){
    this.setData({
      istcVisible2: false,
    });
       
    if(that.data.zskb ==0){
        return;
    }

    setTimeout(this.tc_back,300);

  },
  closeTc3:function(){
      this.setData({
          istcVisible3: false,
      });
  },
  closeTc4:function(){
      this.setData({
          istcVisible4: false,
      });
  },
  closeTc5:function(){
      this.setData({
          istcVisible5: false,
      });
  },
  onShow:function(){
      that = this;

      if(!util.judge.isNull(app.globalData.sxindex) && app.globalData.sxindex==1){
        app.globalData.sxindex=0;
        that.loadData();
      } 
      
      wx.getLocation({
          type: 'wgs84',
          success: function(res) {
              var latitude = res.latitude
              var longitude = res.longitude
              var url = config.url_get_pm25;
              var params = {latitude:latitude,longitude:longitude,uid :wx.getStorageSync('uid')}
                      wxRequest.postRequest(url, params) 
                      .then(res=>{
                          if(res !=2 && util.judge.isObject(res)){
                              that.setData({
                                  pm:res.pm
                                 ,quality:res.quality
                                  ,measure:res.measure
                                  ,affect:res.affect
                                  ,addr:res.city
                                  ,hidpm:false
                              });
                          }
                      })
          }
      })
      
  },
  sbimg:function(){
      wx.getSystemInfo({
          success: function(res) {
              var wh = res.windowHeight;
              //wh = wh - parseInt(wh*0.05);
              //if(wh > that.data.sheight){
                  that.setData({
                      sheight: wh
                  })
              //}
              
          }
      })
  },
  onLoad: function (options) {
      that = this;
      that.data._sdesc="D几名";
      wx.setNavigationBarTitle( { title: that.data._sdesc });

      wx.getSystemInfo({
          success: function(res) {
              var w = parseFloat(res.windowWidth) * 0.95;
              var h = parseFloat( (w * 59 )/100);
              that.setData({
                  swidth:w
                  ,sh :h
              })
          }
      });

      if( !util.judge.isNull(options.dh) ){
          wx.switchTab({
              url: '/pages/index/kbdh'
          })
          return;
      }

      if( !util.judge.isNull(options.scene) ){
          app.getUserInfo()
          .then(res => {
              var scene = decodeURIComponent(options.scene);
              var arrtype = scene.split(",");
              for(var x in arrtype){
                  var temp = arrtype[x];
                  var arr=temp.split("-");
                  if(arr[0]=="u_f" && app.globalData.isnew == 1 ){ //用户分享
                      app.globalData.isnew =0;
                      var fxuid = arr[1];//ajax提交数据库
                      that.data.fxuid= fxuid;
                      wx.getLocation({
                          type: 'wgs84', //返回可以用于wx.openLocation的经纬度
                          success: function(res) {
                              var latitude = res.latitude
                              var longitude = res.longitude
                              var url = config.url_save_user_fx;
                              var params = {fxuid:fxuid,latitude:latitude,longitude:longitude,type:arr[0],isnew:app.globalData.isnew}
                              wxRequest.postRequest(url, params);
                          }
                      })
                  }
              }

              for(var x in arrtype){
                  var temp = arrtype[x];
                  var arr=temp.split("-");
                  if(arr[0]=="uft"  ){ 
                      var fxuid = arr[1];//ajax提交数据库
                      var fxtid = arr[2];
                      var url = config.url_save_user_fx;
                      var params = {fxuid:fxuid,tid:fxtid,type:arr[0]}
                      wxRequest.postRequest(url, params);
                  }
              }

              var zjbs=0;

              for(var x in arrtype){
                  var temp = arrtype[x];
                  var arr=temp.split("-");
                  if(arr[0]=="zjbs"){
                      zjbs=1;
                  }
              }

              for(var x in arrtype){
                  var temp = arrtype[x];
                  var arr=temp.split("-");
                  if(arr[0]=="ti"){
                      var tid = arr[1];
                      wx.redirectTo({
                          url: '../team/view?tid='+ tid+"&zjbs="+zjbs
                      });
                      return;
                  }
              }

              for(var x in arrtype){
                  var temp = arrtype[x];
                  var arr=temp.split("-");
                  if(arr[0]=="dh"){
                      wx.switchTab({
                          url: '/pages/index/kbdh'
                      })
                      return;
                  }
              }

              that.loadData();
          })
          .catch(res => {
          })
          .finally(function (res) {
              
          });
      }else{
          that.loadData();

          
      }

  },
  runcheck:function(){
      if(that.data.tc==1){
          that.setData({
              hidan:true
          })
          util.hideLoading();
          util.alert("手机微信运动数据获取超时！");

          var url = config.url_save_noyd;
          var params = {}
          wxRequest.postRequest(url, params);
      }
      
  },
  runcheck2:function(){
      var url = config.url_user_get;
      var params = {
          id:app.globalData.user.uid
      }
      wxRequest.postRequest(url, params)
      .then(res=>{
          //console.log(res);
          res.dkuser = util.toobj(res.dkuser);
          //console.log(res);
          that.setData({
              'kbobj.kb':res.dkuser.kbnow
          });
          if(res.dkuser && res.dkuser.success ){
              that.setData({
                  'kbobj.kbyd':res.user.ydkb,
                  'kbobj.kbxf':res.dkuser.kball
              });
          }
      
          var bl = false;

          if(res.user.isgl==1){
              bl =true;
          }
       
          that.setData({
              isgl:bl
          })
       
          var url = config.url_get_sysset;
          var params = {}
          return wxRequest.postRequest(url, params);
      })
    .then(res=>{
        console.log(res);
      // res.user 用户的信息  res.dkuser  dk用户的信息
      that.setData({
          sysset:res,
          stepall:res.kblimit
      });

      //计算cake cal
      var cal=0;
      var cake =0;
      var step = that.data.step;
      if(step>0){
        if(that.data.sysset.step_cal){
            cal = step / that.data.sysset.step_cal;
            cal = cal.toFixed(1);
        }

        if(that.data.sysset.step_cake){
            cake = step / that.data.sysset.step_cake;
            cake = cake.toFixed(1);
        }

        that.setData({
            xh_cal:cal,
            xh_cake:cake
        });
      }
      
      //var url = config.url_get_yd_dk_txt;
      //var params = {type:"home_js"}
      //return wxRequest.postRequest(url, params);
    })
    .then(res=>{
        //console.log(res);
        //var article =res.txt1;
       // WxParse.wxParse('article', 'html', article, that, 0);
    })
    .catch(res => {
        console.log(res);
        util.alert_catch(res);
    })
    .finally(function (res) {
        util.hideLoading();
        wx.stopPullDownRefresh();

    });

  },
  loadData:function(){
    app.getUserInfo(false)
    .then(res => {
      if(!util.judge.isObject(res)){
        throw util.stop(); 
      }
     
      var bl = false;
      var bl2 =false;
      if(res.isgl==1){
        bl =true;
      }
      if(res.isadmin ==1){
        var bl2 = true;
      }
      that.setData({
        user:res
        ,userimg:res.img
        ,isgl:bl
        ,isadmin:bl2
      })
      that.data.tc=1;
    })
    .then(res => {
        var url = config.url_get_advertise;
        var params = {
        }
        return wxRequest.postRequest(url, params);
    })
    .then(res => {
        if(util.judge.isObject(res) && res != 1 ){
            //如果用户已经关联 判断是否达到领取k币要求
            //没有关联则跳到注册页面
            app.globalData.tmp.aid=res.id;
            that.data.adurl=res.href;
            var w = parseInt(res.adw);
            var h = parseInt(res.adh);
            var p = parseFloat(res.adp);
            var mw = wx.getSystemInfoSync().windowWidth;

            var bl = w/h;
            var aw = mw * p;
            var ah = aw * h / w;

            //弹出窗口
            var animation = wx.createAnimation({
                timingFunction: "linear",
            })
            animation.scale(0.1, 0.1).step();


            this.setData({
                coverAlphaAnim: animation.export(),
                opop: 1,
                istcVisiblead: true,
                adimg:res.imgurl,
                adw:aw,
                adh:ah
            });

            animation.scale(1, 1).step({ duration: 250 });
            this.setData({
                coverAlphaAnim: animation.export()
            });
        }
        return wxApi.wxGetWeRunData()();
    })
    .then(res => {
        that.data.tc=0;
        that.setData({
            hidan:false
        })
        //util.alert("获取步数成功");
      // if(that.data.encryptedData == res.encryptedData){
      //   throw util.stop();
      // }
      // that.data.encryptedData = res.encryptedData;

      var url = config.url_user_save_run;
      var params = {
       ed: res.encryptedData,
       key: util.getkey(),
       iv:util.getiv()
      }
      return wxRequest.postRequest(url, params);
    })
    .then(res=>{
      console.log(res);
        // var s = util.formatTime(new Date(parseInt(res.timestamp) * 1000));
      if(res.uid==-1){
          wx.clearStorageSync();//清除所有缓存
          wx.redirectTo({
              url: '../index/sq?p=1&url='+ app.globalData.url_https
          });
          throw util.stop();
      }

      var step = parseInt(res.step);
      var kb = parseInt(res.kb);
      if(kb>0){
        kb = true;
      }else{
        kb=false;
      }

      that.setData({
        step:step,
        date:res.udate
        //,isgetkb:kb
      });
      setTimeout(this.runcheck2,100);
      //获取用户的个人信息 包括读取接口
      //var url = config.url_user_get;
      //var params = {
      // id:app.globalData.user.uid
      //}
      //return wxRequest.postRequest(url, params);

    })
    //.then(res=>{
    //    console.log(res);
    //  // res.user 用户的信息  res.dkuser  dk用户的信息
    //  // 
    //  res.dkuser = util.toobj(res.dkuser);
    //  console.log(res);
    //  that.setData({
    //      'kbobj.kb':res.dkuser.kbnow
    //  });
    //  if(res.dkuser && res.dkuser.success ){
    //     that.setData({
    //      'kbobj.kbyd':res.user.ydkb,
    //      'kbobj.kbxf':res.dkuser.kball
    //    });
    //  }
      
    //  var bl = false;

    //  if(res.user.isgl==1){
    //      bl =true;
    //  }
       
    //  that.setData({
    //    isgl:bl
    //  })
       
      //var url = config.url_get_sysset;
      //var params = {}
      //return wxRequest.postRequest(url, params);
    //})
    //.then(res=>{
    //    console.log(res);
    //  // res.user 用户的信息  res.dkuser  dk用户的信息
    //  that.setData({
    //      sysset:res,
    //      stepall:res.kblimit
    //  });

    //  //计算cake cal
    //  var cal=0;
    //  var cake =0;
    //  var step = that.data.step;
    //  if(step>0){
    //    if(that.data.sysset.step_cal){
    //        cal = step / that.data.sysset.step_cal;
    //        cal = cal.toFixed(1);
    //    }

    //    if(that.data.sysset.step_cake){
    //        cake = step / that.data.sysset.step_cake;
    //        cake = cake.toFixed(1);
    //    }

    //    that.setData({
    //        xh_cal:cal,
    //        xh_cake:cake
    //    });
    //  }
      
    //  //var url = config.url_get_yd_dk_txt;
    //  //var params = {type:"home_js"}
    //  //return wxRequest.postRequest(url, params);
    //})
    //.then(res=>{
    //    console.log(res);
    //    var article =res.txt1;
    //    WxParse.wxParse('article', 'html', article, that, 0);
    //})
    .catch(res => {
       
      util.alert_catch(res);
    })
    .finally(function (res) {
      util.hideLoading();
      wx.stopPullDownRefresh();

      

    });
 
  }
  ,btnGetkb:function(e){



    if(that.data.isgl){

      util.showLoading();
      
      var url = config.url_user_save_kb;
      var params = {
       date: that.data.date,
       step: that.data.step,
       fid:e.detail.formId,
       sid:wx.getStorageSync("sid"),
      }

      wxRequest.postRequest(url, params)
      .then(res=>{
        if(util.judge.isObject(res) && res.re == 21){

          // util.alert("当天步数达到"+res.message+"才能领取到Kb哦!");
          that.setData({stepall:res.kblimit});

          var animation = wx.createAnimation({
            timingFunction: "linear",
          })
          animation.scale(0.1, 0.1).step();
          this.setData({
            coverAlphaAnim: animation.export(),
            opop: 1,
            istcVisible: true
          });

          animation.scale(1, 1).step({ duration: 250 });
          this.setData({
            coverAlphaAnim: animation.export()
          }); 
          // return;
        }else if(res==36  ){
            util.alert("请在每天 22:00 前领取K币！");
            that.setData({
                isgetkb:false
            });
        }else if(res==22  ){
            util.alert("您今天已领取所有K币，还请明天再来！");
          that.setData({
            isgetkb:false
          });
        }
        else if( res==31 ){
            util.alert("您今天已领取所有K币，还请明天再来哦！");
            that.setData({
                isgetkb:false
            });
        }
        else if(res==23 ){
            util.alert("网络故障，KB领取失败，请稍后再试！");
            that.setData({
                isgetkb:false
            });
        }
        else if(res==55){
            util.alert("获取系统时间异常，请稍后重试！");
            that.setData({
                isgetkb:false
            });
        }
        else{
          // util.alert("KB领取成功!");
          that.setData({
            'kbobj.kb':that.data.kbobj.kb + res.kb,
            'kbobj.kbyd':that.data.kbobj.ydkb + res.kb,
            getkb:res.kb
          });

          var kbdays =parseInt(res.kbdays);
          var zskb =parseInt(res.zskb);

          var animation = wx.createAnimation({
            timingFunction: "linear",
          })
          animation.scale(0.1, 0.1).step();

          this.setData({
              coverAlphaAnim: animation.export(),
              opop: 1,
              istcVisible2: true ,
              kbdays:kbdays,
              zskb:zskb
          });

          //if(kbdays == 0){
              
          //}else{
          //    this.setData({
          //        coverAlphaAnim: animation.export(),
          //        opop: 1,
          //        istcVisible4: true,
          //        kbdays:kbdays,
          //        zskb:zskb
          //    });
          //}

          animation.scale(1, 1).step({ duration: 250 });
          this.setData({
            coverAlphaAnim: animation.export()
          });
        }
      })
      .catch(res => {
        util.alert_catch(res.message);
      })
      .finally(function (res) {
        util.hideLoading();
      });

    }else{

      wx.navigateTo({
        url: '../user/regnew?back=0'
      })

    }
    

  }
  ,btnTbzh:function(){

  }

  ,btnHb:function(){

    app.getUserInfo()
    .then(res => {
       
        util.showLoading();
      
        var url = config.url_hb_home;
        var params = {
        }
        wxRequest.postRequest(url, params)
        .then(res => {
            // util.alert(res);
            res = app.globalData.url_local+res;
            var arr=[];
            arr.push(res);
            wx.previewImage({
              urls: arr
            })
        })
        .catch(res => {
          util.alert(res.message);
        })
        .finally(function (res) {
          util.hideLoading();
        });
    
    })



   
  }
  ,btnKt:function(){

    if(that.data.isadmin){
      wx.navigateTo({
        url: '../team/edit?tid=0'
      });
    }else{
      $wuxDialog.prompt({
        title: '请输入您的开团授权码', 
        content: '授权码为8位数字', 
        fieldtype: 'number', 
        password: false, 
        defaultText: '', 
        placeholder: '请输入DK提供的授权码', 
        maxlength: 8, 
        onConfirm(e) {
          const value = that.data.$wux.dialog.prompt.response;
            if(value.length != 8){
                util.alert("请输入8位授权码");
                return false;
            }
            
            var url = config.url_sqm_check;
            var params = {
             sqm: value
            }

            wxRequest.postRequest(url, params)
            .then(res=>{
              if(res==21){
                util.alert("授权码不存在，请查证！");
                return false;
              }
              else if(res==22 ){
                  util.alert("授权码已使用，请查证！");
                 return false;
              }
              else if(res==23 ){
                  util.alert("授权码已过期，请查证！");
                 return false;
              }
              else if(res==24 ){
                  util.alert("授权码非开团码，请查证！");
                 return false;
              }
              else{
                //通过验证 
                wx.navigateTo({
                  url: '../team/edit?tid=0&key='+ value
                });

              }
            })
            .catch(res => {
              util.alert(res.message);
            })
            .finally(function (res) {
              util.hideLoading();
            });

        },
      })

    }
  }
  ,btnDayhis:function(){
    wx.navigateTo({
      url: '../user/dayhis'
    })
  }
  ,btnKtlist:function(){
    wx.navigateTo({
      url: '../user/ktlist?type=2'
    })
  },btnSqm:function(){
    wx.navigateTo({
      url: '../user/sqm'
    })
  },
  btnCt:function(){
    wx.navigateTo({
      url: '../user/ktlist?type=1'
    })
  },
   btChart:function(e){
    that.setData({
        cls1:""
      ,cls2:""
      ,cls3:""
      ,cls4:""
    });


    var type = e.currentTarget.dataset.id;

    if(type == 1){
        that.setData({
          'cls1':"bws"
        });
    }

    if(type == 2){
        that.setData({
          'cls2':"bws"
        });
    }

    if(type == 3){
        that.setData({
          'cls3':"bws"
        });
    }

    if(type == 4){
        that.setData({
          'cls4':"bws"
        });

        wx.navigateTo({
          url: '../user/dayhis?type=1'
        })
        return;
    }

    wx.navigateTo({
      url: '../index/chart?type='+type
    })


  },
   btntz:function(e){
       var data = e.currentTarget.dataset;
       var url = data.url;
       util.alert(url);
   },
    //测试模板消息提交form
   formTemplateMessageSubmit:function(e)
   {
       var url = "/WxOpen/TemplateTest";
       var params = {
           sid:wx.getStorageSync("sid"),
           toopenid:"o7zf-0GZ4b_69ixl3t7Dbx1OGnL0"
       }

       wxRequest.postRequest(url, params)
       .then(res=>{

           if(res==1){
               util.alert("已尝试发送模板消息！");
           }
           else{
               util.alert(res.message);
               return false;
           }
       })
       .catch(res => {
           util.alert(res.message);
       })
       .finally(function (res) {
           util.hideLoading();
       });
   }

    ,getRad:function(d){   
       var PI = Math.PI;    
        return d*PI/180.0;    
    }

    ,closeTcad:function(){
        that.setData({
            istcVisiblead: false
        });
        var url = config.url_get_advertise_add;
        var params = {aid:app.globalData.tmp.aid,isok:0}
        wxRequest.postRequest(url, params) 
        .then(res=>{
        });
    }
    ,okTcad:function(){
        var url = config.url_get_advertise_add;
        var params = {aid:app.globalData.tmp.aid,isok:1}
        wxRequest.postRequest(url, params)
        .then(res=>{

        });

        that.setData({
            istcVisiblead: false
        });

        var w="?";
        if(that.data.adurl.indexOf("?")>0){
            w="&";
        }
        var url =that.data.adurl+w+"dxdxdxd="+new Date().getTime();
        app.globalData.tmp.adurl=url;

        wx.switchTab({
            url: '/pages/index/kbdh',
            success:function(){
                
            }
        })

    }

   , bindGetUserInfo: function (e) {
      if (e.detail.userInfo) {
        //用户按了允许授权按钮
        var that = this;
        // 获取到用户的信息了，打印到控制台上看下
        console.log("用户的信息如下：");
        console.log(e.detail.userInfo);
        //授权成功后,跳转页面
        wx.switchTab({
          url: '/pages/home/home',    //这里填入要跳转目的页面的url
          success: (result) => {
            console.log("跳转到首页");
          },
          fail: () => {}
        });
      } else {
        //用户按了拒绝按钮
        wx.showModal({
          title: '警告',
          content: '您拒绝了授权，将无法进入小程序，请授权之后再进入!',
          showCancel: false,
          confirmText: '返回',
          success: function (res) {
            // 用户没有授权成功，不需要改变 isHide 的值
            if (res.confirm) {
              console.log('用户点击了“返回”');
            }
          }
        });
      }
    }
    
,zunew:function(para){
    var params = para;
    util.showLoading();
    var url = config.url_user_save_dknew;
      wxRequest.postRequest(url, params)
      .then(res => {
          that.data.isload = 0;

          var data = res;
          if(data == "24"){
              util.alert("该手机号已经绑定了小程序，不能再次绑定!");
              return false;
          }

          if(data == "25"){
              if(cate=="tb"){
                  util.alert("手机号对应的DK账号不存在，请查证或注册新账号!");
              }else{
                  util.alert("新账号注册失败，请稍后重试!");
              }
              return false;
          }

          if(data == "26"){
              util.alert("该手机号已经绑定小程序，不能再次绑定!");
              return false;
          }


          if(!util.judge.isObject(data)){
              util.alert("数据读取失败，请重试!");
            return false;
          }

          //注册或者同步成功 
          var kbnow = res.kbnow;
          var kbxf = res.kbxf;
          var isnew = res.isnew;
          //这个时候 要调用上个页面的对象 进行同步

          var dd = wx.getStorageSync('data');
          if(!util.judge.isNull(dd)){
              dd.user.isgl=1;
              wx.setStorageSync('data',dd);
          }

          that.setData({
            isgl:1,
            'kbobj.kbxf':kbxf,
            'kbobj.kb':kbnow
          });

          if(that.data.back ==1){
              util.alert("同步成功!",function(){
                  wx.redirectTo({
                      url: '../user/dayhis'
                  });
              });
          }else{
              // var str ="快去领取Kb吧";
              // // if(isnew == "1"){
              // //     str="成功注册新用户，可用您的手机号作为用户名跟密码,登录DK账户，快去领取Kb吧!";
              // // }
              // util.alert(str,function(){
                  
              // });

              // wx.navigateBack({
              //     delta: 1
              // })
          }

      })
      .catch(res => {
          console.log(res);
          util.alert_catch(res);
      })
      .finally(function (res) {
          util.hideLoading();
      });
  }

})